<template>
  <div class="chat-container">
    <div class="content">
      <div v-show="model === 'chat'" class="right">
        <div class="right-list relative">
          <div ref="conversation" class="w-full h-full">111</div>
          <div
            class="community-guide-lines absolute bottom-1 right-1/2 translate-x-1/2 color-#4080FF cursor-pointer z-1"
            @click="handleCommunityGuideLines"
          >
            《社区公约》
          </div>
        </div>

        <div ref="chat" class="right-content" />
        <div v-if="false" v-loading="houseLoading" class="chat-info-wrapper">
          <div v-if="selectedConversation">
            <div class="title">房屋信息</div>
            <div class="info">
              <div class="info-item">
                <span class="label">业主姓名：</span>
                <span class="value">{{ housesInfoList?.house?.ownName }}</span>
              </div>
              <div class="info-item">
                <span class="label">业主手机：</span>
                <span class="value">{{ housesInfoList?.house?.ownMobile }}</span>
              </div>
              <div class="info-item">
                <span class="label">地区：</span>
                <span class="value">{{ housesInfoList.house?.region }}</span>
              </div>
              <div class="info-item">
                <span class="label">小区：</span>
                <span class="value">{{ housesInfoList.house?.neighborhood }}</span>
              </div>
              <div class="info-item">
                <span class="label">门牌号：</span>
                <span class="value">{{ housesInfoList.house?.houseNumber }}</span>
              </div>
              <div class="info-item">
                <span class="label">面积：</span>
                <span class="value">{{ housesInfoList.house?.size || 0 }}平方</span>
              </div>
              <div class="info-item">
                <span class="label">户型：</span>
                <span>{{ housesInfoList.house?.bedroom }}</span>
                室
                <span>{{ housesInfoList.house?.livingRoom }}</span>
                厅
                <span>{{ housesInfoList.house?.bathroom }}</span>
                卫
              </div>
            </div>
            <!-- <div class="title">关联信息</div> -->
            <!-- <el-tabs v-model="activeContact" class="demo-tabs">
              <el-tab-pane
                v-for="(element, i) in housesInfoList.contacts || []"
                :key="i"
                :label="getLabelByValue(CONTACT_TYPE, Number(element.type))"
                :name="i"
              >
                <div class="info">
                  <div class="info-item">
                    <span class="label">姓名：</span>
                    <span class="value">{{ element.name }}</span>
                  </div>
                  <div class="info-item">
                    <span class="label">电话：</span>
                    <span class="value">{{ element.mobile }}</span>
                  </div>
                </div>
              </el-tab-pane> -->
            <div class="title">关联信息</div>
            <div class="info">
              <div class="info-item">
                <span class="label">关联类型：</span>
                <span class="value">
                  {{ CONTACT_TYPE_MESSAGE[housesInfoList.linkInfo?.type] }}
                </span>
              </div>
              <div class="info-item">
                <span class="label">公司名称：</span>
                <span class="value">{{ housesInfoList.linkInfo?.companyName }}</span>
              </div>
              <div class="info-item">
                <span class="label">姓名：</span>
                <span class="value">{{ housesInfoList.linkInfo?.merchantUserName }}</span>
              </div>

              <div class="info-item">
                <span class="label">签约时间：</span>
                <span class="value">{{ housesInfoList.linkInfo?.contractTime }}</span>
              </div>
            </div>
            <div v-show="isDesigner">
              <div class="title">设计机会</div>
              <div class="info">
                <div class="info-item">
                  <span class="label">发布时间：</span>
                  <span class="value">{{ housesInfoList.opportunityDesign?.publishTime }}</span>
                </div>
                <div class="info-item">
                  <span class="label">装修预算(元)：</span>
                  <span class="value">{{ housesInfoList.opportunityDesign?.budget }}</span>
                </div>
              </div>
            </div>
            <div v-show="isPractitioner">
              <div class="title">建材机会</div>
              <div class="info">
                <div class="info-item">
                  <span class="label">品类名称：</span>
                  <span class="value">{{ housesInfoList.opportunityMaterial?.categoryName }}</span>
                </div>
                <div class="info-item">
                  <span class="label">发布时间：</span>
                  <span class="value">{{ housesInfoList.opportunityMaterial?.publishTime }}</span>
                </div>
                <div class="info-item">
                  <span class="label">预算(元)：</span>
                  <span class="value">{{ housesInfoList.opportunityMaterial?.budget }}</span>
                </div>
              </div>
            </div>

            <div class="title">品类信息</div>
            <div class="info">
              <div class="info-item">
                <span class="label">品类名称：</span>
                <span class="value">{{ housesInfoList.category?.name }}</span>
              </div>
              <div class="info-item">
                <span class="label">预算金额(元)：</span>
                <span class="value">
                  {{ housesInfoList.category?.budgetMin }}~{{ housesInfoList.category?.budgetMax }}
                  <span>元</span>
                </span>
              </div>
            </div>
            <!--            <el-tabs v-model="activeName" class="demo-tabs" @tab-change="handleChangeTab">
              <el-tab-pane
                v-for="(item, index) in housesInfoList"
                :key="index"
                :label="item.house.neighborhood"
                :name="index"
              >
                <div class="title">品类信息</div>
                <BasePageTable
                  :table-data="item.designBudgets"
                  :table-columns-data="designBudgetsTableColumnsData"
                ></BasePageTable>
                <div class="title">关联信息</div>
                <el-tabs v-model="activeContact" class="demo-tabs">
                  <el-tab-pane
                    v-for="(element, i) in item.contacts || []"
                    :key="i"
                    :label="getLabelByValue(UserTypeEnum, Number(element.userType))"
                    :name="i"
                  >
                    <div class="info">
                      <div class="info-item">
                        <span class="label">地区：</span>
                        <span class="value">{{ item.house?.region }}</span>
                      </div>
                      <div class="info-item">
                        <span class="label">姓名：</span>
                        <span class="value">{{ element.name }}</span>
                      </div>
                      <div class="info-item">
                        <span class="label">电话：</span>
                        <span class="value">{{ element.mobile }}</span>
                      </div>
                      <div class="info-item">
                        <span class="label">装修公司：</span>
                        <span class="value">{{ element.decorationCompanyName }}</span>
                      </div>
                      <div class="info-item">
                        <span class="label">装修公司地址：</span>
                        <span class="value">{{ element.decorationAddress }}</span>
                      </div>
                    </div>
                  </el-tab-pane>
                </el-tabs>
              </el-tab-pane>
            </el-tabs>-->
          </div>
          <div v-else class="flex-center"><el-empty description="暂无数据" /></div>
        </div>
      </div>
      <div v-show="model === 'contact'" class="right">
        <div ref="contactList" class="right-list" />
        <div ref="contactInfo" class="right-content" />
      </div>
      <div v-if="model === 'collect'" class="collect">
        <div ref="collect" class="collectRight"></div>
      </div>
    </div>
  </div>

  <!-- <div class="customer-service-container">
    <button class="service-button" @mouseenter="showList = true" @mouseleave="showList = false">
      客服
      <span class="arrow" :class="{ 'arrow-up': showList }">▼</span>
    </button>

    <transition name="fade">
      <div
        v-if="showList"
        class="service-list"
        @mouseenter="showList = true"
        @mouseleave="showList = false"
      >
        <div
          v-for="(service, index) in servicesList"
          :key="index"
          class="service-item"
          @click="handleServiceClick(service)"
        >
          <span class="service-icon">👩‍💼</span>
          {{ service.name }}
        </div>
      </div>
    </transition>
  </div> -->
  <el-dialog v-model="dialogVisible" title="常用语" width="35%">
    <BasePageTable
      class="h-full"
      :tableColumnsData="tableColumnsData"
      :pageSize="queryParams.pageSize"
      :tableData="phrasesList"
      :total="total"
      :loading="tableLoading"
      @handleQuery="changePage"
    >
      <template #operation="{ row, name }">
        <el-button type="text" @click="handleSend(row.content)">发送</el-button>
      </template>
    </BasePageTable>
  </el-dialog>
  <Agreement ref="communityGuideLinesRef" keys="merchantCommunityRules"></Agreement>
</template>
<script setup lang="ts">
import { useNimStore } from "@/store/modules/nim";
import "@xkit-yx/im-kit-ui/es/style/css";
import { compile } from "jsx-web-compiler";
import "./iconfont.css";
import ImagePreview from "@/components/ImagePreview/index.vue";
import {
  ChatContainer,
  ContactInfoContainer,
  ContactListContainer,
  ConversationContainer,
} from "@xkit-yx/im-kit-ui";
import { ChatContainerProps } from "@xkit-yx/im-kit-ui/src/chat/Container";
import nimApi, { CustomerRelationQuery, IMQueryParams } from "@/api/nim";
import PhrasesAPI from "@/api/phrases";
import { useRequest } from "@/hooks/useRequest";
import { getLabelByValue } from "../../../utils/enums";
import { CONTACT_TYPE, UserTypeEnum } from "@/enums/system/UserEnum";
import { usePhrases } from "@/hooks/usePhrases";
import BasePageTable from "@/components/BasePageTable/index.vue";
import { useUserStore } from "@/store";
import CommunityGuideLines from "@/views/chat/components/community-guide-lines.vue";
import Agreement from "@/components/Agreement/index.vue";

import { V2NIMConst } from "nim-web-sdk-ng";
const userInfo = useUserStore().userInfo;
const {
  initUiKit,
  login,
  requestPermission,
  sendMessageBySelectedConversation,
  getTeamInfo,
  sendMessage,
} = useNimStore();
const { nimInfo } = storeToRefs(useNimStore());
// const { phrasesList, tableLoading } = usePhrases();
const dialogVisible = ref(false);
const model = ref("chat");
const collect = ref();
const add = ref();
const empty = ref();
const search = ref();
const avatar = ref();
const chat = ref();
const conversation = ref();
const contactList = ref();
const contactInfo = ref();
const phrasesList = ref();
const total = ref(0);
const tableLoading = ref(false);
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
});
const housesInfoList = ref({
  house: "",
});
/*当前活动的会话*/
const selectedConversation = ref("");
const houseLoading = ref(false);
const activeName = ref(0);
const activeContact = ref(0);
const activeCategories = ref(0);
const servicesList = ref([]);
const showList = ref(false);
const communityGuideLinesRef = ref();
let $uikit = initUiKit();

function handleChangeTab(val) {
  activeContact.value = 0;
}

const CONTACT_TYPE_MESSAGE = ref({
  1: "设计师",
  2: "项目经理",
});

/**
 * 设计师显示设计机会，家居建材+从业人员显示建材机会
 */
const isDesigner = computed(() => {
  return userInfo.userType === UserTypeEnum.DESIGNER.value;
});
const isPractitioner = computed(() => {
  return userInfo.userType === UserTypeEnum.PRACTITIONER.value;
});
const isService = computed(() => {
  return housesInfoList.value.houseId;
});
async function getConversationHouses(params: CustomerRelationQuery): Promise<void> {
  try {
    houseLoading.value = true;
    const res = await nimApi.getConversationProfile(params);
    housesInfoList.value = res.data;
  } catch (e) {
    console.log(e);
  } finally {
    houseLoading.value = false;
  }
}

function handleClick() {
  dialogVisible.value = true;
}

function handleSend(message) {
  dialogVisible.value = false;
  sendMessageBySelectedConversation(message);
}

async function getServices() {
  try {
    servicesList.value = await nimApi.getServices();
  } catch (e) {
    console.log(e);
  }
}

async function handleCommunityGuideLines() {
  communityGuideLinesRef.value.showModal();
}

async function handleServiceClick(service) {
  try {
    await nimApi.consultServiceApi({
      conversationId: `${service.accountId}|${V2NIMConst.V2NIMConversationType.V2NIM_CONVERSATION_TYPE_P2P}|${nimInfo.value.accountId}`,
    });
    ElMessage.success("沟通成功");
  } catch (e) {
    console.log(e);
  } finally {
  }
}
function getPhrasersList() {
  tableLoading.value = true;
  try {
    PhrasesAPI.page(queryParams)
      .then((res: any) => {
        total.value = res.total;
        phrasesList.value = res.data;
      })
      .finally(() => {
        tableLoading.value = false;
      });
  } catch (e) {}
}
function changePage(val: any) {
  queryParams.pageNum = val.pageNum;
  queryParams.pageSize = val.pageSize;
  getPhrasersList();
}
onMounted(async () => {
  getPhrasersList();
  getServices();
  requestPermission();
  login();
  $uikit.render(
    ConversationContainer,
    {
      onConversationItemClick: async (id) => {
        try {
          selectedConversation.value = id;
          housesInfoList.value = {
            house: "",
          };
          const [senderId, receiverId] = id.split(/\|[^|]+\|/);
          activeName.value = 0;
          activeContact.value = 0;
          const parts = id.split("|");
          const middleNumber = parts[1];
          if (middleNumber == "1") return;
          const { serverExtension } = await getTeamInfo(receiverId);
          const { id: reqPaymentId } = JSON.parse(serverExtension || "{}");
          const params: CustomerRelationQuery = {
            reqPaymentId,
          };
          if (!reqPaymentId) return;
          getConversationHouses(params);
        } catch (e) {
          console.log("eeee", e);
          ElMessage.error("获取客户信息失败，客户id不存在");
        }
      },
    },
    conversation.value
  );
  $uikit.render(
    ChatContainer,
    {
      strangerTipVisible: false,
      // 以下是自定义渲染，用 compile 函数包裹 html 就可以了，注意 class 要写成 className
      // 安装并引入： import { compile } from "jsx-web-compiler";
      /*renderHeader: (conversation) => {
        console.log("conversation", conversation);
        return compile(`<div className="chat-header-wrap">123</div>`);
      },*/
      actions: [
        {
          action: "emoji",
        },
        {
          action: "sendImg",
        },
        {
          action: "sendFile",
        },
        {
          action: "phrases",
          visible: true,
          render: () => {
            return compile(
              `
            <div className="phrases-wrapper" onClick={context.click}>
            <span className="iconfont-dj icon-changyongyu icon"></span>
</div>
            `,
              { click: handleClick }
            );
          },
        },
        {
          action: "sendMsg",
        },
      ],
      p2pSettingActions: [],
      teamSettingActions: [],
      renderEmpty: () => compile('<div className="empty">暂无数据</div>'),
    } as ChatContainerProps,
    chat.value
  );
  $uikit.render(ContactListContainer, null, contactList.value);
  $uikit.render(
    ContactInfoContainer,
    {
      afterSendMsgClick: () => {
        model.value = "chat";
      },
      onGroupItemClick: () => {
        model.value = "chat";
      },
    },
    contactInfo.value
  );
});
const tableColumnsData = ref([
  {
    prop: "content",
    label: "常用语",
    showOverflowTooltip: true,
  },
  {
    prop: "remark",
    label: "备注",
    showOverflowTooltip: true,
  },
  {
    prop: "operation",
    label: "操作",
    width: 100,
    align: "center",
    fixed: "right",
    customSlot: "operation", // 自定义插槽名称
  },
]);
onBeforeUnmount(() => {
  // 卸载组件
  try {
    $uikit.unmount(chat.value);
    $uikit.unmount(conversation.value);
    $uikit.unmount(contactList.value);
    $uikit.unmount(contactInfo.value);
    $uikit.destroy();
  } catch (e) {
    console.log(e);
  }
});
</script>
<style lang="scss" scoped>
.customer-service-container {
  position: fixed;
  right: 30px;
  bottom: 30px;
  z-index: 1000;
}

.service-button {
  background-color: #409eff;
  color: white;
  border: none;
  border-radius: 20px;
  padding: 10px 20px;
  font-size: 16px;
  cursor: pointer;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
  display: flex;
  align-items: center;
  transition: all 0.3s ease;

  &:hover {
    background-color: #66b1ff;
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.25);
  }
}

.arrow {
  margin-left: 8px;
  font-size: 12px;
  transition: transform 0.3s ease;
}

.arrow-up {
  transform: rotate(180deg);
}

.service-list {
  position: absolute;
  right: 0;
  bottom: 50px;
  width: 200px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  padding: 10px 0;
  overflow: hidden;
}

.service-item {
  padding: 10px 15px;
  color: #333;
  transition: background-color 0.2s;
  display: flex;
  align-items: center;
  cursor: pointer;

  &:hover {
    background-color: #f5f5f5;
  }
}

.service-icon {
  margin-right: 8px;
}

.fade-enter-active,
.fade-leave-active {
  transition:
    opacity 0.3s,
    transform 0.3s;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
  transform: translateY(10px);
}

.chat-container {
  width: 100%;
  height: 100%;
  box-shadow: 0 0 10px 0 rgba(0, 0, 0, 0.1);
  border-radius: 2px;
  background: #fff;
  .header {
    width: 100%;
    height: 60px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-bottom: 1px solid #e8e8e8;

    .search {
      width: 50%;
    }

    .add {
      margin-left: 20px;
    }
  }
  .content {
    width: 100%;
    height: 100%;
    display: flex;

    .left {
      width: 60px;
      border-right: 1px solid #e8e8e8;
      display: flex;
      flex-direction: column;
      align-items: center;
      position: relative;
      box-sizing: border-box;
      min-width: 60px;
    }

    .right-list {
      width: 300px;
      border-right: 1px solid #e8e8e8;
    }

    .right-content {
      flex: 1;
    }
    .right {
      flex: 1;
      display: flex;

      .chat-info-wrapper {
        background: #fff;
        padding: 10px;
        border-left: 1px solid #e8e8e8;
        width: 400px;
      }
    }

    .collect {
      width: 100%;
      height: 100%;
    }
    .collectRight {
      width: 100%;
      height: 100%;
    }
  }
  :deep(.empty) {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
  }
  :deep(.chat-header-wrap) {
    height: 60px;
    display: flex;
    align-items: center;
    font-size: 16px;
    border-bottom: 1px solid #dbe0e8;
    padding-left: 16px;
  }
  :deep(.chat-action-wrap) {
    display: none;
  }
  .title {
    position: relative;
    font-weight: bold;
    font-size: 16px;
    padding-left: 10px;
    &:before {
      content: "";
      position: absolute;
      height: 16px;
      background: #4080ff;
      width: 4px;
      left: 0;
      top: 50%;
      transform: translateY(-50%);
    }
  }

  .info {
    display: flex;
    flex-direction: column;
    gap: 6px;
  }

  .info-item {
    display: flex;
    align-items: center;
    font-size: 14px;
    padding: 2px 0;
    white-space: nowrap; /* 不换行 */
    overflow: hidden; /* 超出隐藏 */
    text-overflow: ellipsis; /* 省略号 */
  }

  .label {
    color: #999;
    flex: 0 0 120px; /* 固定宽度 */
    text-align: right; /* 右对齐 */
    padding-right: 8px; /* 添加一点间距 */
  }

  .value {
    color: #333;
    font-weight: 500;
    flex: 1;
    text-align: left; /* 内容左对齐 */
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  :deep(.phrases-wrapper) {
    width: 20px;
    margin-right: 12px;
    .icon {
      width: 23px;
      color: #656a72;
    }
  }
}
</style>
